/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tomasio.projects.welcome.dao;

import com.tomasio.projects.welcome.dto.CartaoDTO;
import com.tomasio.projects.welcome.model.Cartao;
import com.tomasio.projects.welcome.util.HibernateUtil;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author administrador
 */
public class HibernateCartaoDAO implements CartaoDAO {

    private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    @Override
    public CartaoDTO find(Long id) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        Cartao cartao = (Cartao) session.get(Cartao.class, id);
        tx.commit();
        session.close();
        return cartao.createDTO();
    }

    @Override
    public void create(CartaoDTO cartao) {
        Cartao _cartao = new Cartao(cartao);
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        session.save(_cartao);
        tx.commit();
        session.close();
    }

    @Override
    public void remove(Long id) {
        CartaoDTO dto = find(id);
        Cartao cartao = new Cartao(dto);
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        session.delete(cartao);
        tx.commit();
        session.close();
    }

    @Override
    public void update(CartaoDTO cartao) {
        Cartao _cartao = new Cartao(cartao);
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        session.update(_cartao);
        tx.commit();
        session.close();
    }

    @Override
    public List<CartaoDTO> findAll() {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        List<Cartao> cartoes = session.createQuery("from Cartao cartao").list();
        tx.commit();
        session.close();

        List<CartaoDTO> dtoList = new ArrayList<CartaoDTO>();
        for (Cartao cartao : cartoes) {
            dtoList.add(cartao.createDTO());
        }
        return dtoList;
    }

    @Override
    public CartaoDTO findByNumero(String numero) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        Cartao cartao = (Cartao) session.createQuery("from Cartao cartao where cartao.numero='"
                + numero + "'").uniqueResult();
        tx.commit();
        session.close();
        return cartao.createDTO();
    }
}
